package service

import (
	"task/driver"
	"task/ecode"
	"task/models"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

// ResourceAddRequest resource add request.
type ResourceAddRequest struct {
	DagId int    `json:"dag_id"`
	Name  string `json:"name"`
}

// addResource add resource.
func addResource(c *gin.Context) (interface{}, error) {
	var (
		resourceId int64
		err        error
	)
	// 解析参数
	req := new(ResourceAddRequest)
	if err = c.BindJSON(req); err != nil {
		log.Errorf("AddResource request params error(%v)", err)
		return nil, ecode.ParamsError
	}
	// 检查DAG
	var dag *models.Dag
	if dag, err = driver.GetDag(req.DagId); err != nil {
		return nil, err
	}
	if dag == nil {
		log.Errorf("AddResource dag(%d) not found", req.DagId)
		return nil, ecode.DagNotFound
	}
	// 资源入库
	resourceId = driver.GetSnowFlakeId()
	if err = driver.AddResource(resourceId, req.DagId, req.Name); err != nil {
		return nil, err
	}
	// 发送调度消息(资源添加)
	if err = driver.SendDispatchEventMsg(c, &models.DispatchEvent{
		Event:      models.DispatchEventResourceAdd,
		ResourceId: resourceId,
		DagId:      req.DagId,
	}); err != nil {
		return nil, err
	}
	return resourceId, nil
}
